var app = getApp()
var tabbar = require('../../utils/tabbar');
import _config from '../../utils/config';
import _fetch from '../../utils/httpService';

Page({
  // 页面的初始数据
  data: {
    scrollTop: 0,
    companyName: '',
    orderStatus: false,
    companyList: [],
    acceptNum: 0,
    catchNum: 0,
    switchStatus: '1',
    order: {
      hasButton: true,
      priorityList: ['一般', '紧急', '非常紧急'],
      list: [],
      statusList: [],
      isiOS: app.globalData.isiOS
    },
    acceptList: [],
    grabList: [],
    changeShow: false,
    loading: true,
    waitToDoNum: null,
    companyHeight: '100rpx',
    queryParams: {
      pageSize: 20,
      pageNum: 1,
      orderNo: ''
    },
    isX: false,
    isiOS: false,
    nvabarData: {
      orderNo: '',
      focusSearch: false,
      isSearchClearShow: false
    },
    // 此页面 页面内容距最顶部的距离
    height: app.globalData.height * 2 + 20,
    enterpriseId: null
  },
  // 监听页面加载
  onLoad: function (options) {
    // Do some initialize when page load.
    let vm = this
    tabbar.tabbar("tabBar", 0, this)
    this.setData({
      loading: true,
      isiOS: app.globalData.isiOS,
      enterpriseId: app.globalData.enterpriseId
    })
    wx.showLoading({
      title: '加载中',
    })
    if (app.globalData.formId) {
      if (app.globalData.formAbId) {
        wx.navigateTo({
          url: `../orderDetail/index?id=${app.globalData.formId}&fid=${app.globalData.formAbId}`
        })
      } else {
        wx.navigateTo({
          url: `../orderDetail/index?id=${app.globalData.formId}`
        })
      }
    }
  },
  // 监听页面初次渲染完成
  onReady: function () {
    // Do something when page ready.
  },
  // 监听页面显示
  onShow: function () {
    // Do something when page show.
    let vm = this
    console.log(app.globalData.enterpriseId)
    if (app.globalData.enterpriseId) {
      app.globalData.userData.enterprises.map(i => {
        if (i.id === app.globalData.enterpriseId) {
          vm.setData({
            companyName: i.name,
            companyList: app.globalData.userData.enterprises
          })
        }
      })
    } else {
      this.setData({
        companyName: app.globalData.userData.enterprises[0].name,
        companyList: app.globalData.userData.enterprises
      })
    }
    let hpx = this.data.companyList.length < 4 ? this.data.companyList.length * 108 : 392
    this.setData({
      companyHeight: `${hpx}rpx`,
      'queryParams.pageNum': 1,
      isX: app.globalData.isX
    })
    this.computedNum()
    this.getWorkOrderNum(false)
  },
  // 监听页面隐藏
  onHide: function () {
    // Do something when page hide.
  },
  // 监听页面卸载
  onUnload: function () {
    // Do something when page close.
    this.setData({
      'queryParams.pageNum': 1
    })
  },
  // 监听用户下拉动作
  onPullDownRefresh: function () {
    // Do something when pull down.
  },
  // 页面上拉触底事件的处理函数
  onReachBottom: function () {
    // Do something when page reach bottom.
  },
  onShareAppMessage: function () {
    // 用户点击右上角分享
    return {
      title: '助力企业工单管理智能升级', // 分享标题
      desc: '', // 分享描述
      path: '/pages/login/index', // 分享路径
      imageUrl: '../../img/Mask.png' // 分享图片
    }
  },
  // 页面滚动触发事件的处理函数
  onPageScroll: function () {
    // Do something when page scroll
  },
  // 页面尺寸改变时触发
  onResize: function () {
    // Do something when page resize
  },
  // 当前是 tab 页时，点击 tab 时触发
  onTabItemTap(item) {
    console.log(item.index)
    console.log(item.pagePath)
    console.log(item.text)
  },
  searchList(e) {
    console.log(e)
    if (e && e.detail) {
      this.setData({
        'queryParams.pageNum': 1,
        scrollTop: 0,
      })
      if (e.detail[0] == 'search') {
        this.setData({
          'queryParams.orderNo': e.detail[1]
        })
      } else {
        this.setData({
          'queryParams.orderNo': ''
        })
      }
      setTimeout(() => {
        this.getWorkOrderNum(false)
      }, 0);
    }
  },
  computedNum() {
    let arr = app.globalData.userData.enterprises
    if (arr && arr.length > 0) {
      let num = null
      app.globalData.userData.enterprises.map(i => {
        num = num + i.upcoming
      })
      this.data.waitToDoNum = num
      this.setData({
        waitToDoNum: this.data.waitToDoNum > 99 ? 99 : this.data.waitToDoNum
      })
    }
  },
  showDetail(e) {
    // 跳转至工单详情
    if (e.currentTarget.dataset.formid) {
      if (e.currentTarget.dataset.formAbId) {
        wx.navigateTo({
          url: `../orderDetail/index?id=${e.currentTarget.dataset.formid}&fid=${e.currentTarget.dataset.formAbId}`
        })
      } else {
        wx.navigateTo({
          url: `../orderDetail/index?id=${e.currentTarget.dataset.formid}`
        })
      }
    }
  },
  scrollLoadTop() {
    this.setData({
      'queryParams.pageNum': 1
    })
    this.computedNum()
    this.getWorkOrderNum(false)
  },
  scrollLoadList() {
    // 滚动工单列表事件
    this.setData({
      'queryParams.pageNum': this.data.queryParams.pageNum + 1
    })
    if (this.data.switchStatus === '1') {
      if (this.data.order.list.length !== this.data.acceptNum) {
        this.getWorkOrderNum(true)
      }
    } else {
      if (this.data.order.list.length !== this.data.catchNum) {
        this.getWorkOrderNum(true)
      }
    }
  },
  getWorkOrderNum(isConcat) {
    //获取接抢工单列表
    let vm = this
    _fetch.get(_config.url.get_todo_work, this.data.queryParams)
      .then(function (data) {
        let acceptList = data.acceptPage ? data.acceptPage.rows : [],
          grabList = data.grabPage ? data.grabPage.rows : []
        vm.setData({
          acceptNum: data.acceptPage ? data.acceptPage.total : 0,
          catchNum: data.grabPage ? data.grabPage.total : 0,
          acceptList: acceptList,
          grabList: grabList,
          'order.list': vm.data.switchStatus === '1' ? (isConcat ? vm.data.order.list.concat(acceptList) : acceptList) : (isConcat ? vm.data.order.list.concat(grabList) : grabList),
          'order.buttonType': vm.data.switchStatus
        })
        vm.setData({
          loading: false
        })
        wx.hideLoading()
      }).catch(function (error) {
        console.log(error)
      });
  },
  getPermsList() {
    // 获取权限
    _fetch.get(_config.url.get_perms)
      .then(function (res) {
        console.log(res)
        let permArr = []
        if (res.indexOf('IFORM_ORDER_ACCEPT') > -1) {
          permArr.push('accept', 'refuse') // 受理、拒绝
        }
        if (res.indexOf('IFORM_ORDER_ASSIGN') > -1) {
          permArr.push('assignForm', 'transferForm') // 指派、转派
        }
        if (res.indexOf('IFORM_ORDER_SCRAMBLE') > -1) {
          permArr.push('grabForm') // 抢单
        }
        if (res.indexOf('IFORM_ORDER_RECEIVE') > -1) {
          permArr.push('receiveForm', 'refuseForm') // 接受、拒绝
        }
        if (res.indexOf('IFORM_ORDER_SERVICE') > -1) {
          permArr.push('startService', 'applyException', 'writeProgress', 'completeService') // 开始服务、服务完成、填写进度、申请异常
        }
        if (res.indexOf('IFORM_ORDER_HANDLE_EXCEPTION') > -1) {
          permArr.push('agreeApply', 'rejectApply') // 同意、驳回
        }
        if (res.indexOf('IFORM_ORDER_MESSAGE') > -1) {
          permArr.push('formMessage') // 工单留言
        }
        if (res.indexOf('IFORM_ORDER_CANCEL') > -1) {
          permArr.push('cancelForm') // 取消工单
        }
        if (res.indexOf('IFORM_ORDER_EVALUATE') > -1) {
          permArr.push('evaluateForm') // 评价工单
        }
        console.log(permArr)
        getApp().globalData.perms = permArr;
      }).catch(function (error) {
        wx.showToast({
          title: error.msg,
          icon: 'none',
        });
      });
  },
  hideCatchTabBar(res) {
    // 服务人员不展示接抢单tab
    getApp().globalData.isService = false
    if (res.staff.serviceTeams && res.staff.serviceTeams.length > 0) {
      res.staff.serviceTeams.map(i => {
        if (i.roleInfoOfServiceTeamList && i.roleInfoOfServiceTeamList.length > 0) {
          i.roleInfoOfServiceTeamList.map(j => {
            if (j.code === 'SERVICE_PERSONAL') {
              getApp().globalData.isService = true
            }
          })
        }
      })
    }
    setTimeout(() => {
      if (app.globalData.isService) {
        wx.redirectTo({
          url: '../catchOrder/index'
        })
      } else {
        wx.redirectTo({
          url: '../order/index'
        })
      }
    }, 0);
  },
  enterpriseSwitch(e) {
    // 切换企业
    if (this.data.companyList.length > 1) {
      let vm = this
      let name = e.currentTarget.dataset.ename
      getApp().globalData.enterpriseId = e.currentTarget.dataset.eid
      let url = _config.url.choose_enterprise.replace('{id}', e.currentTarget.dataset.eid);
      _fetch.get(url)
        .then(function (res) {
          getApp().globalData.userData = res;
          vm.hideCatchTabBar(res)
          vm.getPermsList()
          vm.getWorkOrderNum(false)
          vm.closeDialog()
          let hpx = vm.data.companyList.length < 4 ? vm.data.companyList.length * 108 : 392
          vm.setData({
            companyName: name,
            companyList: app.globalData.userData.enterprises,
            companyHeight: `${hpx}rpx`,
            enterpriseId: e.currentTarget.dataset.eid
          })
          vm.computedNum()
        }).catch(function (error) {
          wx.showToast({
            title: error.msg,
            icon: 'none',
          });
        });
    }
  },
  switchOrder(event) {
    if (event.currentTarget.dataset.switch) {
      this.setData({
        switchStatus: event.currentTarget.dataset.switch,
        'queryParams.pageNum': 1
      })
      this.getWorkOrderNum(false)
    } else {
      this.setData({
        switchStatus: '1',
        'queryParams.pageNum': 1
      })
    }
  },
  toChangeCompany() {
    this.setData({
      changeShow: true
    })
  },
  closeDialog() {
    this.setData({
      changeShow: false
    })
  },
  tapARBOrder(e) {
    // 接/拒/抢单
    console.log(e)
    let type = e.currentTarget.dataset.btype
    let id = e.currentTarget.dataset.fid
    let requestData = {
      status: type === 'refuse' ? 0 : 1
    }
    let url = type === 'grab' ? _config.url.grab_work.replace('{id}', id) : _config.url.catch_refuse_work.replace('{id}', id)
    _fetch.put(url, type === 'grab' ? null : requestData).then(() => {
      this.getWorkOrderNum(false)
      wx.hideLoading()
      wx.showToast({
        title: `${type === 'refuse' ? '拒绝' : type === 'grab' ? '抢单' : '接单'}成功`,
        icon: 'none',
        duration: 2000
      })
    }).catch(err => {
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  }
})